package com.xbongbong.formula.qlexpress.operator.math;

import com.alibaba.fastjson.JSON;
import com.ql.util.express.Operator;
import com.xbongbong.formula.enums.MathEnum;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.pro.constant.I18nStringConstant;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: wufeng
 * @date: 2018/7/5 20:16
 * @desrcption:
 */
public class OperatorMinMax extends Operator {

    private static final String MAX = MathEnum.MAX.getFormula();

    private static final String MIN = MathEnum.MIN.getFormula();

    public OperatorMinMax(String name){
        this.name = name;
    }

    public OperatorMinMax(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }

    @Override
    public Object executeInner(Object[] list) throws Exception {
        if (list.length == 0){
            throw new Exception(I18nMessageUtil.getMessage(I18nStringConstant.OPERAND_EXCEPTION));
        }
        List<Object> objectList = new ArrayList<>();
        for (int i = 0; i < list.length; i++){
            Object value = list[i];
            if (value.getClass().isArray()) {
               List<Object> valueList = JSON.parseArray(JSON.toJSONString(value), Object.class);
               objectList.addAll(valueList);
               continue;
            }
            objectList.add(value);
        }
        Object result = objectList.get(0);
        for (int i = 1; i < objectList.size(); i++){
            Object next = objectList.get(i);
            result = executeInner(result, next);
        }
        return result;
    }

    public Object executeInner(Object op1,
                               Object op2) throws Exception {
        Object result = null;
        int compareResult = Operator.compareData(op1,op2);
        if (this.name.equals(MIN)) {
            if (compareResult < 0){
                result = op1;
            } else {
                result = op2;
            }
        } else if (this.name.equals(MAX)) {
            if (compareResult < 0) {
                result = op2;
            } else {
                result = op1;
            }
        }
        return result;
    }
}
